<template>
    <a-modal :keyboard="false" :maskClosable="false" :title="`${modelRef.title}的聊天记录`" :open="visible" :width="800" centered @cancel="handleCancel" :footer="false">
        <div class="custom-dialog-wrapper">
            <a-list item-layout="vertical" size="large" :pagination="false" :data-source="modelRef.item">
                <template #renderItem="{ item }">
                    <a-list-item :key="item.msgtime">
                        <template #extra>
                            <div style="max-width: 250px" v-if="item.type === 'ChatRecordImage'">
                                <a-image :height="150" :src="item.content.media_network_path" />
                            </div>
                            <a-button type="link" v-if="item.type === 'ChatRecordFile'" @click="handleDownload(item.content)">此消息暂不支持显示，请点击下载查看</a-button>
                            <div class="chatMessage" v-if="item.type === 'ChatRecordText'">{{ toStringJSON(item.content)?.content || '' }}</div>
                        </template>
                        <a-list-item-meta :description="item.description">
                            <template #title></template>
                        </a-list-item-meta>
                    </a-list-item>
                </template>
            </a-list>
        </div>
    </a-modal>
</template>

<script lang="ts" setup>
    import { reactive, ref } from 'vue';
    import dayjs from 'dayjs';
    import { toStringJSON } from 'xe-utils';

    const visible = ref<boolean>(false);

    const emit = defineEmits(['cancel', 'success']);

    const modelRef = reactive<any>({});

    const handleDownload = item => {
        const link = document.createElement('a');
        link.href = item.media_network_path;
        link.download = item?.filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };
    const handleCancel = () => {
        emit('cancel');
        visible.value = false;
        Object.keys(modelRef).forEach(key => {
            delete modelRef[key];
        });
        Object.assign(modelRef, {});
    };

    const init = async data => {
        console.log(data);

        Object.assign(modelRef, data, {
            item: data.item.map(item => {
                return {
                    ...item,
                    description: dayjs(item.msgtime * 1000).format('YYYY-MM-DD HH:mm:ss'),
                };
            }),
        });
        visible.value = true;
    };

    defineExpose({
        init,
    });
</script>
